package ClientManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
public class RegionSocketManager {
    public Socket socket = null;
    private BufferedReader input = null;
    private PrintWriter output = null;
    private boolean isRunning = false;
    private Thread infoListener;

    private String region;
    public RegionSocketManager() {

    }

    public void setRegionIP(String ip) {
        this.region = ip;
    }

    //region的端口号固定为6666
    public boolean connectRegionServer(String address) throws IOException ,ConnectException{
        String[] ips = address.split(":");
        String ip = ips[0];
//        int port = Integer.parseInt(ips[1]);
        int port = 6666;
    try{
        socket = new Socket(ip, port);
        socket.sendUrgentData(0xFF);
    }
    catch(ConnectException se){
        return false;
    }
    catch (Exception e) {
        e.printStackTrace();
    }
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new PrintWriter(socket.getOutputStream(), true);
        isRunning = true;
        this.listenToRegion();
        System.out.println("Connect to region, ip: " + ip + " port: " + port);
        return true;
    }


    public void receiveFromRegion() throws IOException {
        String line = new String("");
        if (socket.isClosed() || socket.isInputShutdown() || socket.isOutputShutdown()) {
            System.out.println("Socket closed!");
        } else {
            StringBuilder sb = new StringBuilder();
            while(!(line = input.readLine()).equals("")){
                sb.append(line).append("\n");
            }
            line = sb.toString();
        }
        if (line != null) {
            if(line.startsWith("<R2C>[6]")){
                System.out.println("Receive from Region:");
                System.out.print(line.substring(8));
            }
            //print result
//            String prompt="";
//            int width=10;//每个字段值10个空间
//            if(line.contains("|")){
//                String []values=line.split("\\|");
//                System.out.println(prompt);
//                for (int i=1;i<values.length;i++){
//                    // values[i]=values[i].substring(1);
//                    System.out.printf("|%s",StringUtils.center(values[i],width));
//                }
//                System.out.printf("|%n");
//            }
//            else{
//                if(line.equals("-----")) {System.out.println(prompt);}
//                else{System.out.println(prompt+line);
//                }
//            }

        }
    }

    public void listenToRegion() {
        infoListener = new InfoListener();
        infoListener.start();
    }

    public void closeRegionSocket() throws IOException {
        socket.shutdownInput();
        socket.shutdownOutput();
        socket.close();
        infoListener.stop();
    }

    //type为6表示select，type为12表示其他数据库操作语句
    public void sendToRegion(String info,int type) {
        System.out.println("Send to Region: " + info);
        output.println("<C2R>["+type+"]"+info);
    }


    class InfoListener extends Thread {
        @Override
        public void run() {
            System.out.println("Listening from region...");
            while (isRunning) {
                if (socket.isClosed() || socket.isInputShutdown() || socket.isOutputShutdown()) {
                    isRunning = false;
                    break;
                }

                try {
                    receiveFromRegion();
                } catch (SocketException e) {
                    isRunning = false;
//                    e.printStackTrace();
                } catch (IOException e){
//                    e.printStackTrace();
                }
                try {
                    sleep(100);
                } catch (InterruptedException | NullPointerException e) {
//                    e.printStackTrace();
                }
            }
        }
    }
}
